Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Note that you cannot sell a stock before you buy one.
給定陣列,代表每天的股價,在只能有一次交易的條件下,最多能賺多少錢?
Input: [7,1,5,3,6,4]
Output: 5
Input: [7,6,4,3,1]
Output: 0
先設定最大獲利與最低價格,再依序比較陣列的每個值,每次的迴圈,都會找出目前的最大獲利與最低價格。
var maxProfit = function (prices) {
let maxProfit = 0;
let minPrice = prices[0];
for (let i = 1; i < prices.length; i++) {
minPrice = minPrice < prices[i] ? minPrice : prices[i];
maxProfit = prices[i] - minPrice > maxProfit ? prices[i] - minPrice : maxProfit;
}
return maxProfit;
};